<?php

/**
 * @version     1.0.4
 * @package     com_hotels
 * @copyright   Copyright (C) 2014. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 * @author      Russell English <russell.english@stormit.co.uk> - http://www.stormit.co.uk
 */
defined('_JEXEC') or die;

jimport('joomla.application.component.modellist');

/**
 * Methods supporting a list of Hotels records.
 */
class HotelsModelAvailable extends JModelList {

    /**
     * Constructor.
     *
     * @param    array    An optional associative array of configuration settings.
     * @see        JController
     * @since    1.6
     */
    public function __construct($config = array()) {
        if (empty($config['filter_fields'])) {
            $config['filter_fields'] = array(
                'mykey', 'a.mykey',
                'hotelcode', 'a.hotelcode',
                'stgcode', 'a.stgcode',
                'hotelname', 'a.hotelname',
                'resortcode', 'a.resortcode',
                'resortname', 'a.resortname',
                'dep', 'a.dep',
                'arr', 'a.arr',
                'startdate', 'a.startdate',
                'enddate', 'a.enddate',
                'brochureprice', 'a.brochureprice',
                'discount', 'a.discount',
                'sellingprice', 'a.sellingprice',
                'seats', 'a.seats',
                'rooms', 'a.rooms',
                'beds', 'a.beds',
                'available', 'a.available',
                'entry', 'a.entry',
                'active', 'a.active',
                'originalprice', 'a.originalprice',
                'id', 'a.id',
                'ordering', 'a.ordering',
                'state', 'a.state',
                'created_by', 'a.created_by',

            );
        }
        parent::__construct($config);
    }

    /**
     * Method to auto-populate the model state.
     *
     * Note. Calling getState in this method will result in recursion.
     *
     * @since   1.6
     */
    protected function populateState($ordering = null, $direction = null) {

        // Initialise variables.
        $app = JFactory::getApplication();

        // List state information
        $limit = $app->getUserStateFromRequest('global.list.limit', 'limit', $app->getCfg('list_limit'));
        $this->setState('list.limit', $limit);

        $limitstart = JFactory::getApplication()->input->getInt('limitstart', 0);
        $this->setState('list.start', $limitstart);


        if(empty($ordering)) {
            $ordering = 'a.ordering';
        }

        // List state information.
        parent::populateState($ordering, $direction);
    }

    /**
     * Build an SQL query to load the list data.
     *
     * @return  JDatabaseQuery
     * @since   1.6
     */
    protected function getListQuery($dateRange = false, $otherResorts = false) {

        // Create a new query object.
        $db = $this->getDbo();
        $query = $db->getQuery(true);

        // Select the required fields from the table.
        $query
            ->select(
            $this->getState(
                'list.select', 'DISTINCT a.*'
            )
        );

        $query->from('`#__availability` AS a');


        // Join over the users for the checked out user.
        $query->select('uc.name AS editor');
        $query->join('LEFT', '#__users AS uc ON uc.id=a.checked_out');

        // Join over the created by field 'created_by'
        $query->join('LEFT', '#__users AS created_by ON created_by.id = a.created_by');

        // Filter by published state
        $published = $this->getState('filter.state');
        if (is_numeric($published)) {
            $query->where('a.state = '.(int) $published);
        } else {
            $query->where('(a.state = 1)');
        }


        // Filter by search in title
        $search = $this->getState('filter.search');
        if (!empty($search)) {
            if (stripos($search, 'id:') === 0) {
                $query->where('a.id = ' . (int) substr($search, 3));
            } else {
                $search = $db->Quote('%' . $db->escape($search, true) . '%');
                $query->where('( a.hotelname LIKE '.$search.'  OR  a.resortname LIKE '.$search.'  OR  a.dep LIKE '.$search.' )');
            }
        }



        //Filtering startdate
        $filter_startdate_from = $this->state->get("filter.startdate.from");
        if ($filter_startdate_from) {
            $query->where("a.startdate >= '".$filter_startdate_from."'");
        }
        $filter_startdate_to = $this->state->get("filter.startdate.to");
        if ($filter_startdate_to) {
            $query->where("a.startdate <= '".$filter_startdate_to."'");
        }

        // Add the list ordering clause.
        $orderCol = $this->state->get('list.ordering');
        $orderDirn = $this->state->get('list.direction');
        if ($orderCol && $orderDirn) {
            $query->order($db->escape($orderCol . ' ' . $orderDirn));
        }

        // Get Joomla input factory
        $input = JFactory::getApplication()->input;

        // Get resort input with default value 'A' and filtered as string
        $resort = $input->get('resort', 'A', 'string');

        // If value other than default is set, apply condition
        if ( $resort !== 'A' ) {
        
          if ($otherResorts) {
            $query->where('a.resortName != ' . $db->quote($resort));
          }
          else
            $query->where('a.resortName = ' . $db->quote($resort));
        }

        // Get airport input with default value 'A' and filtered as string
        $airport = $input->get('airport', 'A', 'string');

        if ( $airport !== 'A' ) {
            $query->where('a.dep = ' . $db->Quote($airport));
        }

        // Get searchdate input with default value 'A' and filtered as string
        $date = $input->get('searchdate', 'A', 'string');

        if ( $date !== 'A' ) {
           if ($dateRange) {
              $dFrom = date("Y-m-d", strtotime($date)-60*60*24*$dateRange);
              $dTo = date("Y-m-d", strtotime($date)+60*60*24*$dateRange);

              $query->where('a.startDate >= ' . $db->Quote($dFrom));
              $query->where('a.startDate <= ' . $db->Quote($dTo));
           }
           else
              $query->where('a.startDate = ' . $db->Quote($date));
        }

        // Get passegners input
        $adults = $input->get('numadults', 2, 'uint');
        $child = $input->get('numchild', 0, 'uint');
        $infants = $input->get('numinfants', 0, 'uint');

        // Sum adults, childs and infants
        $passengers = $adults + $child + $infants;

        // Apply condition
        $query->where('a.seats >= ' . $passengers);
        $query->where('a.beds >= ' . $passengers);

        return $query;
    }
    /**
     * getSimilarList - get list of similar results
     **/
    public function getSimilarList() {
      $db = $this->getDbo();
      $query = str_replace("#__", $db->getPrefix(), $this->getListQuery(7));
      $db->setQuery($query);
      $out['other_dates'] = $db->loadObjectList();

      $query = str_replace("#__", $db->getPrefix(), $this->getListQuery(false, true));
      $db->setQuery($query);
      $out['other_resorts'] = $db->loadObjectList();

      return $out;
    }

    public function getItems() {
        $items = parent::getItems();

        return $items;
    }

}
